<?
function getValue($value_name, $data_type = "int", $method = "GET", $default_value = 0, $advance = 0){
	$value = $default_value;
	switch($method){
		case "GET": if(isset($_GET[$value_name])) $value = $_GET[$value_name]; break;
		case "POST": if(isset($_POST[$value_name])) $value = $_POST[$value_name]; break;
		case "COOKIE": if(isset($_COOKIE[$value_name])) $value = $_COOKIE[$value_name]; break;
		case "SESSION": if(isset($_SESSION[$value_name])) $value = $_SESSION[$value_name]; break;
		default: if(isset($_GET[$value_name])) $value = $_GET[$value_name]; break;
	}
	$valueArray	= array("int" => intval($value), "str" => trim(strval($value)), "flo" => floatval($value), "dbl" => doubleval($value), "arr" => $value);
	foreach($valueArray as $key => $returnValue){
		if($data_type == $key){
			if($advance != 0){
				switch($advance){
					case 1:
						$returnValue = replaceMQ($returnValue);
						break;
					case 2:
						$returnValue = htmlspecialbo($returnValue);
						break;
				}
			}
			//Do số quá lớn nên phải kiểm tra trước khi trả về giá trị
			if((strval($returnValue) == "INF") && ($data_type != "str")) return 0;
			return $returnValue;
			break;
		}
	}
	return (intval($value));
}
function removeAccent($mystring){
	$marTViet=array(
		// Chữ thường
		"à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă","ằ","ắ","ặ","ẳ","ẵ",
		"è","é","ẹ","ẻ","ẽ","ê","ề","ế","ệ","ể","ễ",
		"ì","í","ị","ỉ","ĩ",
		"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ","ờ","ớ","ợ","ở","ỡ",
		"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
		"ỳ","ý","ỵ","ỷ","ỹ",
		"đ","Đ","'",
		// Chữ hoa
		"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă","Ằ","Ắ","Ặ","Ẳ","Ẵ",
		"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
		"Ì","Í","Ị","Ỉ","Ĩ",
		"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ","Ờ","Ớ","Ợ","Ở","Ỡ",
		"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
		"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
		"Đ","Đ","'"
		);
	$marKoDau=array(
		/// Chữ thường
		"a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a",
		"e","e","e","e","e","e","e","e","e","e","e",
		"i","i","i","i","i",
		"o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o","o",
		"u","u","u","u","u","u","u","u","u","u","u",
		"y","y","y","y","y",
		"d","D","",
		//Chữ hoa
		"A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","A",
		"E","E","E","E","E","E","E","E","E","E","E",
		"I","I","I","I","I",
		"O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O",
		"U","U","U","U","U","U","U","U","U","U","U",
		"Y","Y","Y","Y","Y",
		"D","D","",
		);
	return str_replace($marTViet, $marKoDau, $mystring);
}

function removeHTML($string){
	$string = preg_replace ('/<script.*?\>.*?<\/script>/si', ' ', $string);
	$string = preg_replace ('/<style.*?\>.*?<\/style>/si', ' ', $string);
	$string = preg_replace ('/<.*?\>/si', ' ', $string);
	$string = str_replace ('&nbsp;', ' ', $string);
	$string = mb_convert_encoding($string, "UTF-8", "UTF-8");
	$string = str_replace (array(chr(9),chr(10),chr(13)), ' ', $string);
	for($i = 0; $i <= 5; $i++) $string = str_replace ('  ', ' ', $string);
	return $string;
}
function decode_entities($text) {
    $text= html_entity_decode($text,ENT_QUOTES,"UTF-8"); #NOTE: UTF-8 does not work!
    $text= preg_replace('/&#(\d+);/me',"chr(\\1)",$text); #decimal notation
    $text= preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$text);  #hex notation
    return $text;
}
function redirect($url){
	$url	= htmlspecialbo($url);
	echo '<script type="text/javascript">window.location.href = "' . $url . '";</script>';
	exit();
}
function replaceMQ($text){
	$text	= str_replace("\'", "'", $text);
	$text	= str_replace("'", "''", $text);
	return $text;
}
/*
Remove HTML truoc khi add vao database
*/
function htmlspecialbo($str){
	$arrDenied	= array('<', '>', '"');
	$arrReplace	= array('&lt;', '&gt;', '&quot;');
	$str = str_replace($arrDenied, $arrReplace, $str);
	return $str;
}

function resize($img, $w, $h, $newfilename) {
 
 //Check if GD extension is loaded
 if (!extension_loaded('gd') && !extension_loaded('gd2')) {
  trigger_error("GD is not loaded", E_USER_WARNING);
  return false;
 }
 
 //Get Image size info
 $imgInfo = getimagesize($img);
 switch ($imgInfo[2]) {
  case 1: $im = imagecreatefromgif($img); break;
  case 2: $im = imagecreatefromjpeg($img);  break;
  case 3: $im = imagecreatefrompng($img); break;
  default:  trigger_error('Unsupported filetype!', E_USER_WARNING);  break;
 }
 
 //If image dimension is smaller, do not resize
 if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
  $nHeight = $imgInfo[1];
  $nWidth = $imgInfo[0];
 }else{
    if($imgInfo[0] != 0 && $imgInfo[1] !=0){
        if($w / $imgInfo[0] > $h / $imgInfo[1]) $percent = $h / $imgInfo[1];
        else $percent = $w / $imgInfo[0];
    }
 
     $nWidth    = $imgInfo[0] * $percent;
     $nHeight   = $imgInfo[1] * $percent;
 }
 $nWidth = round($nWidth);
 $nHeight = round($nHeight);
 $newImg = imagecreatetruecolor($nWidth, $nHeight);
 
 /* Check if this image is PNG or GIF, then set if Transparent*/  
 if(($imgInfo[2] == 1) OR ($imgInfo[2]==3)){
  imagealphablending($newImg, false);
  imagesavealpha($newImg,true);
  $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
  imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
 }
 imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
 
 //Generate the file, and rename it to $newfilename
 switch ($imgInfo[2]) {
  case 1: imagegif($newImg,$newfilename); break;
  case 2: imagejpeg($newImg,$newfilename);  break;
  case 3: imagepng($newImg,$newfilename); break;
  default:  trigger_error('Failed resize image!', E_USER_WARNING);  break;
 }
   
   return $newfilename;
}
//In mảng
	function echoArray($array){
		if(!empty($array)){
			echo "<pre>";
			print_r($array);
			echo "</pre>";
		}else{
			echo "ko co hang";
		}
	}
 // Tra ve tat ca so san pham hien tai
 function countProduct(){
   $count = 0;
   $db_sel = new db_query("SELECT count(pro_id) as count FROM product");
   $array = mysql_fetch_assoc($db_sel->result);
   $count = $array['count'];
   return $count;
 }  
  // Tra ve tat ca so bai viet hien hien tai
 function countAticle(){
   $count = 0;
   $db_sel = new db_query("SELECT count(art_id) as count FROM article");
   $array = mysql_fetch_assoc($db_sel->result);
   $count = $array['count'];
   return $count;
 }  
 // Tra ve mang cac product theo type
 function getProduct($cat_id='',$limit='',$order=''){
    if($limit != '') $limit  = ' LIMIT '. $limit;
    if($order != '') $order  = ' ORDER BY ' . $order . ' DESC ';
    $arrResult = array();
    if($cat_id == ''){
        $db_sel = new db_query("SELECT *
                                FROM product INNER JOIN category ON pro_cat_id = cat_id $order $limit");
    }else{
        $db_sel = new db_query("SELECT *
                                FROM product INNER JOIN category ON pro_cat_id = cat_id 
                                WHERE pro_cat_id=" . $cat_id . $limit);
    }
    
    $arrResult = $db_sel->resultArray();
    unset($db_sel);
    return $arrResult;
 }
  // Tra ve mang cac product theo type
 function getArticle($art_id=0,$limit=''){
    if($limit != '') $limit  = ' LIMIT '. $limit;
    $arrResult = array();
    if($art_id == 0){
        $db_sel = new db_query("SELECT *
                                FROM article ORDER BY art_id DESC $limit");
    }else{
        $db_sel = new db_query("SELECT *
                                FROM article WHERE art_id = $art_id ORDER BY art_id DESC $limit");
    }
    
    $arrResult = $db_sel->resultArray();
    unset($db_sel);
    return $arrResult;
 }
 // Tra ve tat ca cac cate
 function getCate($cat_id = 0){
   $arr_result = array();
   if($cat_id == 0)
      $db_sel     = new db_query("SELECT * FROM category ORDER BY cat_position DESC");
   else
      $db_sel     = new db_query("SELECT * FROM category WHERE cat_id = $cat_id");
   $arr_result = $db_sel->resultArray('cat_id');
   return $arr_result;
 }
 // Tra ve mang cac product theo ten san pham
 function getProductName($product_name,$order=''){
    if($order != '') $order  = ' ORDER BY ' . $order . ' DESC ';
    $arrResult = array();
    $db_sel = new db_query("SELECT *
                            FROM product INNER JOIN category ON pro_cat_id = cat_id
                            WHERE pro_name LIKE '%" . $product_name . "%' $order");

    $arrResult = $db_sel->resultArray();
    unset($db_sel);
    return $arrResult;
 }
 // function tra ve anh cua san pham duoi dang html
 function showImagePro($string,$path,$class='',$width='80px',$height='50px'){
   $arr_name = explode(',',$string);
   foreach($arr_name as $value){
      echo '<img class="'.$class.'" style="margin-right:10px;" width="'.$width.'" height="'.$height.'" src="' . $path. $value .'"/>';
   }
 }
 // function in ra anh thumb cua san pham
 function PrintImageThumbPro($string,$path,$class='',$alt=''){
   $arr_name = explode(',',$string);
   echo '<img class="'.$class.'" alt="'.$alt.'" src="' . $path . $arr_name[0] .'"/>';
 }
 
 // function xoa những ảnh cũ khi đã được thay thế bằng ảnh khác
 function delImagePro($string,$path){
   $arr_name = explode(',',$string);
   foreach($arr_name as $value){
      if(file_exists($path.$value))
         unlink($path.$value);
      if(file_exists($path.'small_'.$value))
         unlink($path.'small_'.$value);
      if(file_exists($path.'medium_'.$value))
         unlink($path.'medium_'.$value);
   }
 }
 // Tra ve mang cac product theo id
 function getProductId($product_id=''){
   $arrResult = array();
   $db_sel = new db_query("SELECT *
                                FROM product INNER JOIN category ON pro_cat_id = cat_id
                                WHERE pro_id=" . $product_id);
   while($row = mysql_fetch_assoc($db_sel->result)){
     $arrResult['pro_id']        = $row['pro_id'];
     $arrResult['pro_code']      = $row['pro_code'];
     $arrResult['pro_name']      = $row['pro_name'];
     $arrResult['pro_price']     = $row['pro_price'];
     $arrResult['pro_origin']    = $row['pro_origin'];
     $arrResult['pro_gua']       = $row['pro_gua'];
     $arrResult['pro_pic']       = $row['pro_pic'];
     $arrResult['pro_pic_1']     = $row['pro_pic_1'];
     $arrResult['pro_pic_2']     = $row['pro_pic_2'];
     $arrResult['pro_num_sold']  = $row['pro_num_sold'];
     $arrResult['pro_des']       = $row['pro_des'];
     $arrResult['pro_content']   = $row['pro_content'];
     $arrResult['cat_id']        = $row['cat_id'];
     $arrResult['cat_name']      = $row['cat_name'];
   }
   unset($db_sel);
   return $arrResult;
 }
 // rewrite link san pham
 function rewriteDetailProduct($name,$id){
    $link ='/san-pham/'.str_replace(' ','-',removeAccent($name)).'-'.urlencode($id).'.html';
    return $link;
 }
 // rewrite link cate
 function rewriteCate($cat_name,$cat_id){
    $link ='/danh-muc/'.urlencode($cat_id).'/'.str_replace(' ','-',removeAccent($cat_name)).'.html';
    return $link;
 }  
 function cut_string($str, $length, $char=" ..."){
	//Nếu chuỗi cần cắt nhỏ hơn $length thì return luôn
	$strlen	= mb_strlen($str, "UTF-8");
	if($strlen <= $length) return $str;

	//Cắt chiều dài chuỗi $str tới đoạn cần lấy
	$substr	= mb_substr($str, 0, $length, "UTF-8");
	if(mb_substr($str, $length, 1, "UTF-8") == " ") return $substr . $char;

	//Xác định dấu " " cuối cùng trong chuỗi $substr vừa cắt
	$strPoint= mb_strrpos($substr, " ", "UTF-8");

	//Return string
	if($strPoint < $length - 20) return $substr . $char;
	else return mb_substr($substr, 0, $strPoint, "UTF-8") . $char;
}
// dinh dang html
function format_html($str){
    $arr_search     = array('&lt;','&gt;');
    $arr_replace    = array('<','>');
    $str = str_replace($arr_search,$arr_replace,$str);
    return $str;
}
// decode_html
function decode_html($text) {
    $text= html_entity_decode($text,ENT_QUOTES,"UTF-8"); #NOTE: UTF-8 does not work!
    $text= preg_replace('/&#(\d+);/me',"chr(\\1)",$text); #decimal notation
    $text= preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$text);  #hex notation
    return $text;
}
function format_number($number,$char = '.'){
   return number_format($number,0,',',$char);
}
function deleleFile($path, $filename){
   unlink($path.$filename);
}
function generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous='<', $next='>', $first='<<', $last='>>', $break_type=1, $page_rewrite=0, $page_space=3, $obj_response='', $page_name="page"){

	$page_query_string	= "&" . $page_name . "=";
   //Kiem tra url neu chua co dau ? thi chuoi ket noi la dau ?
	if(strpos($url, "?") <= 0)	$charquery	=	"?";
	//Kiem tra neu ket thuc cua url la / thi ko them gi ca
	if(substr($url, strlen($url) - 1) == "/")	$charquery	=	"";
	$page_query_string	= $charquery . $page_name . "=";
	// Nếu dùng ModRewrite thì dùng dấu , để phân trang
	if($page_rewrite == 1) $page_query_string = "=";

	if($total_record % $page_size == 0) $num_of_page = $total_record / $page_size;
	else $num_of_page = (int)($total_record / $page_size) + 1;

	//$page_space = 7;

	$start_page = $current_page - $page_space;
	if($start_page <= 0) $start_page = 1;

	$end_page = $current_page + $page_space;
	if($end_page > $num_of_page) $end_page = $num_of_page;

	// Remove XSS
	$url = str_replace('\"', '"', $url);
	$url = str_replace('"', '', $url);

	if($break_type < 1) $break_type = 1;
	if($break_type > 4) $break_type = 4;

	// Pagebreak bar
	$page_bar = "";

	// Write prefix on screen
	if($page_prefix != "") $page_bar .= '<font class="' . $normal_class . '">' . $page_prefix . '</font> ';

	// Write frist page
	if($break_type == 1){
		if(($start_page != 1) && ($num_of_page > 1)){
			if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . '1' . '\',\'' . $obj_response . '\')';
			else $href = $url . $page_query_string . '1';
			$page_bar .=  '<a href="' . $href . '" class="' . $normal_class . ' firstpage" title="First page">' . $first . '</a> ';
		}
	}

	// Write previous page
	if($break_type == 1 || $break_type == 2 || $break_type == 4){
		if(($current_page > 1) && ($num_of_page > 1)){
			if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . ($current_page - 1) . '\',\'' . $obj_response . '\')';
			else $href = $url . $page_query_string . ($current_page - 1);
			$page_bar .= ' <a href="' . $href . '" class="' . $normal_class . ' prevpage" title="Prev page">' . $previous . '</a> ';
			if(($start_page > 1) && ($break_type == 1 || $break_type == 2)){
				$page_dot_before = $start_page - 1;
				if($page_dot_before < 1) $page_dot_before = 1;
				if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . $page_dot_before . '\',\'' . $obj_response . '\')';
				else $href = $url . $page_query_string . $page_dot_before;
				$page_bar .= '<a href="' . $href . '" class="' . $normal_class . ' notUndeline">...</a> ';
			}
		}
	}

	// Write page numbers
	if($break_type == 1 || $break_type == 2 || $break_type == 3){
		$start_loop = $start_page;
		if($break_type == 3) $start_loop = 1;
		$end_loop	= $end_page;
		if($break_type == 3) $end_loop = $num_of_page;
		for($i=$start_loop; $i<=$end_loop; $i++){
			$j = ($i < 10) ? "0" . $i : $i;
			if($i != $current_page){
				if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . $i . '\',\'' . $obj_response . '\')';
				else $href = $url . $page_query_string . $i;
				$page_bar .= ' <a href="' . $href . '" class="' . $normal_class . '">' . $j . '</a> ';
			}
			else{
				$page_bar .= ' <font class="' . $selected_class . '">' . $j . '</font> ';
			}
		}
	}

	// Write next page
	if($break_type == 1 || $break_type == 2 || $break_type == 4){
		if(($current_page < $num_of_page) && ($num_of_page > 1)){
			if(($end_page < $num_of_page) && ($break_type == 1 || $break_type == 2)){
				$page_dot_after = $end_page + 1;
				if($page_dot_after > $num_of_page) $page_dot_after = $num_of_page;
				if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . $page_dot_after . '\',\'' . $obj_response . '\')';
				else $href = $url . $page_query_string . $page_dot_after;
				$page_bar .= '<a href="' . $href . '" class="' . $normal_class . ' notUndeline">...</a> ';
			}
			if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . ($current_page + 1) . '\',\'' . $obj_response . '\')';
			else $href = $url . $page_query_string . ($current_page + 1);
			$page_bar .= ' <a href="' . $href . '" class="' . $normal_class . ' nextpage" title="Next page">' . $next . '</a> ';
		}
	}

	// Write last page
	if($break_type == 1){
		if(($end_page < $num_of_page) && ($num_of_page > 1)){
			if($obj_response != '') $href = 'javascript:load_data(\'' . $url . $page_query_string . $num_of_page . '\',\'' . $obj_response . '\')';
			else $href = $url . $page_query_string . $num_of_page;
			$page_bar .= ' <a href="' . $href . '" class="' . $normal_class . ' lastpage" title="Last page">' . $last . '</a>';
		}
	}

	// Return pagebreak bar
	return $page_bar;
}
// tra ve mang san pham theo full-text search
   function searchProFullText($keyword){
      $arrResult = array();
      $db_sel = new db_query("SELECT *,MATCH(pro_name) AGAINST('" . $keyword . "' IN BOOLEAN MODE) as point FROM product 
                              WHERE MATCH(pro_name) AGAINST('" . $keyword . "' IN BOOLEAN MODE)
                              HAVING point >= 1 
                              ORDER BY point DESC ");
      $arrResult = $db_sel->resultArray();
      unset($db_sel);
      return $arrResult;
      
   }
// tra ve mang san pham theo search LIKE
   function searchProLike($keyword){
      $arrResult = array();
      $db_sel = new db_query("SELECT * FROM product WHERE pro_name LIKE '%".$keyword."%' ");
      $arrResult = $db_sel->resultArray();
      unset($db_sel);
      return $arrResult;
   }
// function chèn logo vào ảnh
   function image_overlap($path, $filename){
		
		// Nếu tồn tại foreground thì mới overlap
		if(file_exists($this->foreground)){
			
			$background		= $this->create_image($path, $filename);
			if(!$background) return;
			
			// Chèn ảnh overlap vào
			$foreground		= imagecreatefrompng($this->foreground);
			$insertWidth	= imagesx($foreground);
			$insertHeight	= imagesy($foreground);
			$imageWidth		= imagesx($background);
			$imageHeight	= imagesy($background);
			$overlapX		= 5;
			$overlapY		= $imageHeight - $insertHeight - 5;
			
			imagecolortransparent($foreground, imagecolorat($foreground, 0, 0));
			imagecopy($background, $foreground, $overlapX, $overlapY, 0, 0, $insertWidth, $insertHeight);
			
			$this->output_image($background, $path, $filename);
			
			// Hủy biến để giải phóng bộ nhớ
			unset($background);
			unset($foreground);
			
		}
	}
?>